# Copyright 2025 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Test data worker."""

import os

import numpy as np
import pytest
import random

import mindspore as ms
from mindspore.dataset.dataloader import DataLoader, Dataset, IterableDataset, get_worker_info
from mindspore.dataset.dataloader._utils.worker import WorkerInfo, WorkerException
from mindspore.dataset.dataloader._utils.bit_generator import seed_sequence
from tests.mark_utils import arg_mark


@arg_mark(plat_marks=["cpu_linux"], level_mark="level0", card_mark="onecard", essential_mark="essential")
@pytest.mark.parametrize("worker_id", tuple(range(4)))
def test_seed_sequence(worker_id):
    """
    Feature: Test generate state.
    Description: Test generate the state with the given base seed and worker id.
    Expectation: The result is as generated by numpy.
    """
    base_seed = random.getrandbits(32)
    state = seed_sequence(base_seed, worker_id)
    np_state = np.random.bit_generator.SeedSequence(
        [worker_id, base_seed & 0xFFFFFFFF, base_seed >> 32, 0]
    ).generate_state(4)
    np.testing.assert_array_equal(np.array(state), np_state)


class WorkerInfoDataset(Dataset):
    """A dataset for testing worker info."""

    def __init__(self, num_samples):
        super().__init__()
        self.num_samples = num_samples

    def __getitem__(self, index):
        return self.result

    def __len__(self):
        return self.num_samples


class WorkerInitFnDataset(IterableDataset):  # pylint: disable=abstract-method
    """A dataset for testing worker init function."""

    def __init__(self, num_samples):
        super().__init__()
        self.num_samples = num_samples
        self.start = 0
        self.end = num_samples
        self.step = 1

    def __iter__(self):
        return iter(range(self.start, self.end, self.step))


class TestWorker:
    """Test Worker."""

    @arg_mark(plat_marks=["cpu_linux"], level_mark="level0", card_mark="onecard", essential_mark="essential")
    def test_worker_init_fn(self):
        """
        Feature: Test worker init function.
        Description: Test set the step and start of the dataset in the worker init function.
        Expectation: The result is as expected.
        """

        def worker_init_fn(worker_id):
            worker_info = get_worker_info()
            num_workers = worker_info.num_workers
            dataset = worker_info.dataset
            dataset.step = num_workers
            dataset.start = 0 + worker_id

        num_samples = 10
        dataset = WorkerInitFnDataset(num_samples)
        data_loader = DataLoader(dataset, num_workers=4, worker_init_fn=worker_init_fn)
        for index, data in enumerate(data_loader):
            assert data == ms.tensor([index])

    @arg_mark(plat_marks=["cpu_linux"], level_mark="level0", card_mark="onecard", essential_mark="essential")
    @pytest.mark.parametrize("num_workers", (1, 2))
    def test_worker_info(self, num_workers):
        """
        Feature: Test worker info.
        Description: Test change the attributes of the dataset in the worker init function.
        Expectation: The result is as expected.
        """

        def worker_init_fn(worker_id):
            worker_info = get_worker_info()
            assert worker_info.id == worker_id
            assert worker_info.num_workers == num_workers
            assert worker_info.seed == ms.initial_seed()
            assert worker_info.dataset.__class__ == WorkerInfoDataset
            worker_info.dataset.result = [worker_id, os.getpid()]

        dataset = WorkerInfoDataset(10)
        data_loader = DataLoader(dataset, num_workers=num_workers, worker_init_fn=worker_init_fn)
        itr = iter(data_loader)
        assert get_worker_info() is None
        for data in itr:
            worker_id, worker_pid = data
            assert itr.data_workers[worker_id].pid == worker_pid
        assert not hasattr(dataset, "result")

    @arg_mark(plat_marks=["cpu_linux"], level_mark="level0", card_mark="onecard", essential_mark="essential")
    def test_worker_info_repr(self):
        """
        Feature: Test worker info repr.
        Description: Test printing the worker info.
        Expectation: The result is as expected.
        """
        worker_info = WorkerInfo(id=0, num_workers=4, seed=0, dataset=None)
        assert str(worker_info) == "WorkerInfo: {id: 0, num_workers: 4, seed: 0, dataset: None}"

    @arg_mark(plat_marks=["cpu_linux"], level_mark="level0", card_mark="onecard", essential_mark="essential")
    def test_worker_info_unmodifiable(self):
        """
        Feature: Test worker info unmodifiable.
        Description: Test modifying the attributes of the worker info.
        Expectation: Raise RuntimeError.
        """
        worker_info = WorkerInfo(id=0, num_workers=4, seed=0, dataset=None)
        with pytest.raises(
            RuntimeError, match="Cannot modify the attributes of WorkerInfo object after initialization"
        ):
            worker_info.id = 2

    @arg_mark(plat_marks=["cpu_linux"], level_mark="level0", card_mark="onecard", essential_mark="essential")
    @pytest.mark.parametrize("exc_type", (ValueError, TypeError, RuntimeError, OSError))
    def test_worker_exception(self, exc_type):
        """
        Feature: Test worker exception.
        Description: Test raising exception in the worker.
        Expectation: Raise RuntimeError.
        """
        worker_id = 0
        msg = "We have trouble"

        with pytest.raises(
            RuntimeError,
            match=rf"DataLoader worker {worker_id} \(pid: .*\) caught {exc_type.__name__} with message:(\n|.)*{msg}",
        ):
            try:
                raise exc_type(msg)
            except Exception:  # pylint: disable=W0703
                worker_exception = WorkerException(worker_id=worker_id)
                worker_exception.reraise()
